<?php

namespace App\Kuafu\User\Controller\Merchant;

use App\Exceptions\BaseException;
use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Log\Model\UserLoginLogModel;
use App\Kuafu\Log\Service\UserLoginLogService;
use App\Kuafu\Sms\Service\SmsService;
use App\Kuafu\User\Enum\CodeEnum;
use App\Kuafu\User\Enum\UserCodeEnum;
use App\Kuafu\User\Exceptions\AuthException;
use App\Kuafu\User\Exceptions\UserException;
use App\Kuafu\User\Model\User;
use App\Kuafu\User\Service\AuthService;
use App\Kuafu\User\Service\UserService;
use App\Kuafu\User\Support\NetEaseDun;
use App\Kuafu\User\Validate\UserValidate;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Psr\SimpleCache\InvalidArgumentException;

class LoginController extends BaseController
{
    /**
     * 用户登录
     * @param Request $request
     * @return JsonResponse
     */
    public function login(Request $request)
    {
        $valid = UserValidate::loginValid($request);
        if ($valid) {
            return $this->fail(UserCodeEnum::ERR_SERVER_ERROR, $valid);
        }
        $type = $request->type ?: 1;
        if ($type == CodeEnum::LOGIN_TYPE_PWD) {
            $res = AuthService::login($request, UserCodeEnum::MERCHANT_TYPE, $request->isLasting);
        } else {
            $mobile = $request->username;
            SmsService::verifyCode($mobile, $request->code, SmsService::CODE_TYPE_MODIFY_LOGIN);
            $res = AuthService::mobileLogin($mobile, UserCodeEnum::MERCHANT_TYPE, $request->isLasting, (string)$request->ip());
        }
        $expiredTimestamp = time() + (config('jwt.ttl') * 60);
        //判断是否为首次登录
        $isFirstLogin = UserService::isFirstLogin($request) ? UserLoginLogModel::USER_LOGIN_FIRST_YSE : UserLoginLogModel::USER_LOGIN_FIRST_NO;
        return $this->success(['token'            => $res,
                               'expiredTimestamp' => $expiredTimestamp,
                               'isFirstLogin'     => $isFirstLogin
        ]);
    }

    /**
     * 退出登录
     */
    public function logout(Request $request)
    {
        AuthService::logout();
        return $this->success();
    }

    public function refresh(Request $request)
    {
        $res              = AuthService::refresh();
        $expiredTimestamp = time() + (config('jwt.ttl') * 60);
        return $this->success(['token' => $res, 'expiredTimestamp' => $expiredTimestamp]);
    }


    /**
     * 飞书登陆
     *
     * @param Request $request
     * @return JsonResponse
     * @throws AuthException
     * @throws UserException
     * @throws BaseException
     * @throws GuzzleException
     * @throws InvalidArgumentException
     */
    public function fsLogin(Request $request): JsonResponse
    {
        $code = $request->post("code", "");
        $ip   = (string)$request->ip();

        $res  = AuthService::fsLogin($code, UserCodeEnum::MERCHANT_TYPE, $ip);

        return $this->success([
            'token'            => $res,
            'expiredTimestamp' => time() + CodeEnum::KEEP_LOGIN_TIME,
            'isStaff'          => true
        ]);
    }

    /**
     * 网易盾登录
     * @param Request $request
     * @return JsonResponse
     */
    public function netEaseDun(Request $request)
    {
        $token       = (string)$request->get('token');
        $accessToken = (string)$request->get('accessToken');
        $ip          = (string)$request->ip();

        $this->validate($request, [
            'token'       => 'required|string',
            'accessToken' => 'required|string',
        ]);

        $data = (new NetEaseDun())->getPhone($token, $accessToken);
        if (!$data['code']) {
            return $this->fail(500, $data['msg']);
        }
        $phone = $data['data']['phone'] ?? '';

        // TODO 登录需要调试效果
        if (empty($phone)) {
            Log::warning("netEaseDun err:", $data);
            // 取号失败,建议进行二次验证,例如短信验证码
            return $this->fail(500, '取号失败,建议进行二次验证,例如短信验证码');
        }

        $res              = AuthService::mobileLogin($phone, UserCodeEnum::MERCHANT_TYPE, 1, $ip);
        $expiredTimestamp = time() + (config('jwt.ttl') * 60);

        //判断是否为首次登录
        $request->username = $phone;
        try {
            $isFirstLogin = UserService::isFirstLogin($request) ? UserLoginLogModel::USER_LOGIN_FIRST_YSE : UserLoginLogModel::USER_LOGIN_FIRST_NO;
        } catch (\Exception $e) {
            $isFirstLogin = 0;
        }

        return $this->success([
            'token'            => $res,
            'expiredTimestamp' => $expiredTimestamp,
            'isFirstLogin'     => $isFirstLogin
        ]);
    }
}
